/*
 * @Author: i@douxuefeng.cn
 * @Date: 2022-06-02 14:56:06
 * @LastEditTime: 2024-05-24 17:24:07
 * @LastEditors: Please set LastEditors
 * @Description:
 * @FilePath: \go-utils\wechat\mp\template_msg\template_msg.go
 */
package template_msg

import (
	"encoding/json"
	"errors"
	"fmt"

	"gitee.com/douxuefeng/go-utils/request"
	"gitee.com/douxuefeng/go-utils/wechat/mp/accesstoken"
	"gitee.com/douxuefeng/go-utils/wechat/mp/mpconfig"
	"gitee.com/douxuefeng/go-utils/wechat/mp/params"
)

type templateMsg struct {
	*mpconfig.MpConfig
}

func NewTemplateMsg(cfg *mpconfig.MpConfig) *templateMsg {
	return &templateMsg{cfg}
}

const (
	templateMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
)

func (mp *templateMsg) Send(data params.TemplateMsgParams) error {
	token, err := accesstoken.GetAccessToken(mp.MpConfig)
	if err != nil {
		return err
	}
	url := templateMsgUrl + token
	req := request.NewRequest()
	req.SetBody(data)
	res, err := req.Post(url)
	if err != nil {
		return err
	}
	var rs params.Err
	fmt.Println("res:====", res.String())
	json.Unmarshal(res.Body(), &rs)
	if rs.Errcode != 0 {
		return errors.New(rs.Errmsg)
	}
	return nil
}
